import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import BasicLayout from '../layouts/BasicLayout.vue'
// import BlankLayout from '../layouts/BlankLayout.vue'
import WelcomePage from '../views/welcome.vue'
// import { userStore } from '@/store/modules/user';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

// only githubpages preview site used, if use template please remove this check
// and use `createWebHistory` is recommend
// const hasGithubPages = import.meta.env.VITE_GHPAGES

const baseRouter = [
  {
    path: '/Login',
    name: 'Login',
    meta: { title: 'Login' },
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/404',
    name: '404',
    meta: {
      title: 'Page not found'
    },
    component: () => import('@/views/404.vue')
  }
]

const errorRouter = {
  path: '/:pathMatch(.*)*',
  name: 'catch404',
  redirect: '/404'
}

const router = createRouter({
  // history: hasGithubPages ? createWebHashHistory() : createWebHistory(),
  history: createWebHashHistory(),
  routes: [...baseRouter]
})

const modules = import.meta.glob('../views/**/*.vue')

function getRouetByMenuListLoop(children) {
  return children.map((v) => {
    const obj = {
      name: v.name,
      path: '/' + v.url,
      key: v.id,
      meta: {
        title: v.name,
        icon: v.icon
      },
      component: modules[`../views/${v.url}.vue`]
    }
    if (v.children && v.children.length) {
      obj['children'] = getRouetByMenuListLoop(v.children)
    }

    return obj
  })
}

function getRouetByMenuList(menuList) {
  const asyncRoutes = getRouetByMenuListLoop(menuList)
  const home = {
    path: '/',
    name: 'index',
    meta: { title: '首页' },
    component: BasicLayout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        meta: { title: '欢迎', icon: 'icon-shouye' },
        component: WelcomePage
      }
    ]
  }
  home.children = [...home.children, ...asyncRoutes]
  return { menus: asyncRoutes, routers: home }
}

export function resetRouter(menuList) {
  // const initRouter = createRouter({
  //   // history: hasGithubPages ? createWebHashHistory() : createWebHistory(),
  //   history: createWebHashHistory(),
  //   routes: [...baseRouter, getRouetByMenuList(menuList), ...errorRouter]
  // })
  // router.options.routes = initRouter.options.routes
  const { menus, routers } = getRouetByMenuList(menuList)

  router.addRoute(routers)
  router.addRoute(errorRouter)
  return menus
}

export function initRouter() {
  router.hasRoute('index') && router.removeRoute('index')
  router.hasRoute('catch404') && router.removeRoute('catch404')
}

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '美联数字医疗科技有限公司'
  }
  if (to.query.token && to.query.orgId) {
    store.userStore.token = to.query.token
    store.userStore.orgId = to.query.orgId
    to.query.f1 && (store.userStore.from1 = to.query.f1)
    to.query.f2 && (store.userStore.from2 = to.query.f2)
    to.query.platformId && (store.userStore.platformId = to.query.platformId)
  }
  if (store.userStore.token) {
    if (to.path === '/Login') {
      store.userStore.LoginOut()
      next('/Login')
      // window.location.href = store.userStore.from1 + '#' + store.userStore.from2
    } else {
      if (!store.userApp.userInfo) {
        await store.userApp.GetUserInfo()
        await store.userApp.GetMenuList()
        await store.userApp.GetPermissionList()
        await store.userApp.getDietDict() // 获取食谱字段数据
        await store.userApp.getSportDict() // 获取运动字段数据

        if (to.path === '/') {
          next('/home')
        } else {
          if (to.query.token) {
            to.query = {}
          }
          next({ ...to, replace: true })
        }
      } else {
        if (to.path === '/') {
          next('/home')
        } else {
          next()
        }
      }
    }
  } else {
    initRouter()
    if (import.meta.env.MODE == 'dev') {
      if (to.path != '/login') {
        next({ path: '/login' })
      } else {
        next()
      }
    } else {
      window.location.href = store.userStore.from1 + '#' + store.userStore.from2
    }
  }
  // 如果用户未能验证身份，则 `next` 会被调用两次
})

router.afterEach((to, from) => {
  NProgress.done()
})

export default router
